package com.topisv.tms.service.edi.ocr;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.EdiOrderItemDao;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.redis.RedisEdiOrdenoService;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.utils.rule.CreateOrdeno;
import com.topisv.tms.utils.rule.TMSRule;
import com.topisv.tms.webservice.soap.response.vo.ReturnMessage;

@Component
@Transactional(readOnly = true)
public class AddOCROrdenoImpl {

	@Autowired
	private EdiOrderDao ediOrderDao;
	@Autowired
	private AreaService areaService;
	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private RedisEdiOrdenoService redisEdiOrdenoService;
	@Autowired
	private TMSRule tmsRule;
	@Autowired
	private EdiOrderItemDao ediOrderItemDao;

	@Transactional(readOnly = false)
	public ReturnMessage addOCROrdeno(String key, String secret, String message)
			throws Exception {
		List<EdiOrder> objList = null;
		ReturnMessage returnMessage = null;
		try {
			returnMessage = new ReturnMessage();
			message=message.replaceAll("四少11省","四川省").replaceAll("少I?I","州").replaceAll("少I?","州").replaceAll("州?I","州");
			if (message.startsWith("{")) {
				JSONObject jsonMessage = JSONObject.fromObject(message);
				EdiOrder ediOrder = (EdiOrder) JSONObject.toBean(jsonMessage,EdiOrder.class);
				save(ediOrder, "ocr", key);
			} else {
				objList = JsonUtil.getList(message, EdiOrder.class);
				save(objList, "ocr", key);
			}
			returnMessage.setStatus("1");
			returnMessage.setReson("接收成功");

		} catch (Exception e) {
			throw e;
		}

		return returnMessage;
	}

	private String getAreaType(String areaName, String areaType)
			throws Exception {
		try {
			Area area = areaService.getTopArea(areaName, areaType);
			if (area != null) {
				return area.getAreaCode();
			}
			return null;
		} catch (Exception e) {
			throw e;
		}
	}

	@Transactional(readOnly = false)
	public void save(List<EdiOrder> ediOrders, String type, String customerCode)
			throws Exception {
		try {
			for (EdiOrder ediOrderOCR : ediOrders) {
				save(ediOrderOCR, type, customerCode);
			}
		} catch (Exception e) {
			throw e;
		}
	}

	@Transactional(readOnly = false)
	public void save(EdiOrder ediOrder, String type, String customerCode)
			throws Exception {
		try {
			
			
			String provCode = getAreaType(ediOrder.getProvna(), "2");
			if (provCode == null) {
				provCode = getAreaType(ediOrder.getCityna(), "3");
				if (provCode != null) {
					Area area = areaService.findByAreaCode(provCode);
					area = areaService.getArea(area.getArea().getId());
					if(area!=null){
						provCode = area.getAreaCode();
					}
				}
			}
			if (provCode == null) {
				provCode = "pending";
			}
			ediOrder.setProvco(provCode);// 设置省编码

			// 得到最大运单号
			String maxWaybillNo = ediOrderDao.findMaxWaybillNo(customerCode);
			Customers customers = customersDao.findByCustomerCode(customerCode);
			String waybill=ediOrder.getWaybillNo();
			if(!(waybill==null||"".equals(waybill)||waybill.length()!=(customers.getStartNumber()+customers.getEndNumber()).length())){
				if (maxWaybillNo == null|| "".equals(maxWaybillNo)||is(waybill, maxWaybillNo)) {
					if(null!=ediOrder.getWaybillNo()){
						String waybillNo = ediOrder.getWaybillNo().substring(customers.getStartNumber().length());
						customers.setEndNumber(waybillNo);
						customersDao.save(customers);
					}
					
				}
			}else{
				ediOrder.setGymemo("0");
			}
		
			String bz=ediOrder.getShmemo();
			if(bz!=null){
				if(bz.indexOf(customers.getForwardSign())>=0){
					ediOrder.setForwardSign("forward");// 中转发订单
				}
			}
			
			Date nowDate = new Date();
			ediOrder.setCustomerCode(customerCode);
			ediOrder.setErpType(type);
			ediOrder.setCrtime(nowDate);
			ediOrder.setPatime(nowDate);
			ediOrder.setAdtime(nowDate);
			ediOrder.setOrderStatus("ok");
			ediOrder.setStatus("pending");
			
			String customerOrdeno=ediOrder.getOrdeno();
			
			List<EdiOrder> orders = ediOrderDao.findByCustomerCodeAndCustomerOrdeno(customerCode, ediOrder.getOrdeno());
			EdiOrder tempEdiOrder = orders.isEmpty()? null : orders.get(0);
			if (tempEdiOrder != null) {
				if("finish".equals(tempEdiOrder.getStatus())){
					ediOrder.setStatus("finish");
				}
				ediOrder.setId(tempEdiOrder.getId());
				ediOrder.setOrdeno(tempEdiOrder.getOrdeno());
			}else{
				CreateOrdeno.setOrdenrOrdeno(ediOrder, tmsRule);//能容订单号
			}
			 
			List<EdiOrderItem> edis=ediOrderItemDao.findByCustomerCodeAndOrdeno(customerCode, customerOrdeno);
			if(edis!=null&&!edis.isEmpty()){
				for(EdiOrderItem edi:edis){
					edi.setOrdeno(ediOrder.getOrdeno());
					ediOrderItemDao.save(edi);
				}
		    }
			ediOrderDao.save(ediOrder);
		} catch (Exception e) {
			throw e;
		}
	}

	private boolean is(String waybillNo, String maxWaybill) {
		if(waybillNo==null||"".equals(waybillNo)){
			return false;
		}
		if (Long.parseLong(maxWaybill) < Long.parseLong(waybillNo)) {
			return true;
		}
		return false;
	}
}
